
/* This is an example of how to cancel all the files queued up.  It's made somewhat generic.  Just pass your SWFUpload
object in to this method and it loops through cancelling the uploads. */
function cancelQueue(instance) {
	document.getElementById(instance.customSettings.cancelButtonId).disabled = true;
	instance.stopUpload();
	var stats;
	
	do {
		stats = instance.getStats();
		instance.cancelUpload();
	} while (stats.files_queued !== 0);
	totalSize = 0;
	clearQueue(instance);
}

/**
处理UI，刪除表格的所有行(文件列表)
**/
function  clearQueue(instance){
	var listingfiles = document.getElementById(instance.customSettings.progressTarget);
	var rowLength = listingfiles.rows.length;
	while(rowLength>0){
		listingfiles.deleteRow(0);
		rowLength--;
	}
	showInfo(0,0);

}


/* **********************
   Event Handlers
   These are my custom event handlers to make my
   web application behave the way I went when SWFUpload
   completes different tasks.  These aren't part of the SWFUpload
   package.  They are part of my application.  Without these none
   of the actions SWFUpload makes will show up in my application.
   ********************** */
function fileDialogStart() {
	/* I don't need to do anything here */
}

var totalSize=0;
function fileQueued(file) {
	try {

		totalSize+=file.size;
		var listingfiles = document.getElementById(this.customSettings.progressTarget);	
		//取得index.html中的fileList（文件列表）对象
		var tr = listingfiles.insertRow();
		tr.id=file.id;
		
		var flag = tr.insertCell(); flag.className='flag2';
		
		var fileName = tr.insertCell();
		fileName.innerHTML=file.name;
		
		var progressTD = tr.insertCell();
		progressTD.className='progressTD';
		progressTD.innerHTML='<span id="' + file.id +'progress" class="progressBar"></span><span>'+getNiceFileSize(file.size)+'</span>';
		
		var del = tr.insertCell(); 
		del.className='delectBtn';//调用css
		del.id=file.id +'deleteGif'; 
		del.innerHTML='<a href="javascript:upload1.cancelUpload(\'' + file.id + '\', true)"><img src="images/del_ico.gif" alt="清除" width="13" height="13" border="0" /></a>';
		showInfo(file, listingfiles.rows.length);
	
	} catch (ex) {
		this.debug(ex);
	}

}


/**
显示信息
**/
function showInfo(file,queuelength){
	var fileCount = document.getElementById("fileCount");//文件总数
	fileCount.innerText=queuelength;
	var fileTotleSize = document.getElementById("fileTotleSize");
	fileTotleSize.innerText = getNiceFileSize(totalSize);//文件大小(byte,Kb.Mb等转换)
}

function fileQueueError(file, errorCode, message) {
	try {
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			alert("您的选择不能超过 "  + message + " 图片." );
			return;
		}

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			progress.setStatus("File is too big.");
			this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			progress.setStatus("Cannot upload Zero Byte files.");
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus("Invalid File Type.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
			alert("You have selected too many files.  " +  (message > 1 ? "You may only add " +  message + " more files" : "You cannot add any more files."));
			break;
		default:
			if (file !== null) {
				progress.setStatus("Unhandled Error");
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if (this.getStats().files_queued > 0) {
			document.getElementById(this.customSettings.cancelButtonId).disabled = false;
		}
		
		/* I want auto start and I can do that here */
		//this.startUpload();
	} catch (ex)  {
        this.debug(ex);
	}
}

function uploadStart(file) {
	try {
		window.status='正在上传文件'+file.name+'....';
	}
	catch (ex) {
	}
	
	return true;
}

function uploadProgress(file, bytesLoaded, bytesTotal) {

	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
		
		var progress = document.getElementById(file.id + "progress");	
		progress.style.backgroundPositionX=(percent-100)+'px';
		
		//var progress = new FileProgress(file, this.customSettings.progressTarget);
		//progress.setProgress(percent);
		//progress.setStatus("Uploading...");

	} catch (ex) {
		this.debug(ex);
	}
}


/**
上传文件完成时
*/
function uploadSuccess(file, serverData) {
	try {
		//var progress = new FileProgress(file, this.customSettings.progressTarget);
		//progress.setComplete();
		//progress.setStatus("Complete.");
		//progress.toggleCancel(false);

		var tR = document.getElementById(file.id);
		tR.className += " fileUploading";
		tR.cells(0).className='flag1';		
		var progress = document.getElementById(file.id + "progress");	
		progress.style.backgroundPositionX='0px';
		//cancelImage;
		var deleteImg = document .getElementById(file.id + 'deleteGif'); 
	    deleteImg.innerHTML = "";	
		//alert(file.id+" "+file.name+"上传成功:"+serverData);
		
		var returnFile = {};
		returnFile.name = file.name;
		returnFile.serverPath = serverData;
		returnFiles.push(returnFile);

	} catch (ex) {
		this.debug(ex);
	}
}

function uploadComplete(file) {
	try {
		
		/*  I want the next upload to continue automatically so I'll call startUpload here */
		if (this.getStats().files_queued === 0) {
			document.getElementById(this.customSettings.cancelButtonId).disabled = true;
		} else {	
			this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}

}

/**
某个上传文件被取消时执行方法
**/
function uploadFileCancelled(file, instance) {   
	var listingfiles = document.getElementById(instance.customSettings.progressTarget);
	
	var rows = listingfiles.rows;
	for(var i=rows.length-1;i>=0;i--){
		if(file.id==rows[i].id){
			listingfiles.deleteRow(i);
			//扣除Filesize 
			totalSize = totalSize -file.size;
			break;
		}
	}	
	showInfo(file, listingfiles.rows.length);
}


function uploadError(file, errorCode, message) {
	try {
		//var progress = new FileProgress(file, this.customSettings.progressTarget);
		//progress.setError();
		//progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			alert("上传错误: " + message);
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
			alert("设置错误!");
			this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			alert("上传失败");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			alert("服务器（IO）错误");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			alert("安全性问题错误");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			alert("上传文件超过限制,一次性上传10个文件，每个文件不超过100M");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
			alert("没有该文件");
			this.debug("Error Code: The file was not found, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			alert("Failed Validation.  Upload skipped.");
			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			if (this.getStats().files_queued === 0) {
				document.getElementById(this.customSettings.cancelButtonId).disabled = true;
			}
			uploadFileCancelled(file,this);
			//alert("Cancelled");
			//progress.setStatus("Cancelled");
			//progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			alert("Stopped");
			break;
		default:
			alert("Unhandled Error: " + error_code);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

var _K = 1024;
var _M = _K*1024;
function getNiceFileSize(bitnum){
	if(bitnum<_M){
		if(bitnum<_K){
			return bitnum+'B';
		}else{
			return Math.ceil(bitnum/_K)+'K';
		}
		
	}else{
		return Math.ceil(100*bitnum/_M)/100+'M';
	}	
}